/**
 * This program is free software but WITHOUT ANY WARRANTY OR CONDITIONS OF ANY KIND.
 *
 * Copyright (C) 2008-2012 www.pretty-tools.com
 */

const nsISupportsCString = Components.interfaces.nsISupportsCString;
const nsIFilePicker = Components.interfaces.nsIFilePicker;

/**
 * Save image to disk.
 *
 * @author Alexander Kozlov
 */
var wsshSaveImageHelper = {
    logger: yrprxFactory.createLogger("wsshSaveImageHelper"),
    baseName: "", // prefix for generated files
    suffix: 0 // suffix for generated files
};

wsshSaveImageHelper.getExtension = function (uriObject)
{
    var ext;

    try
    {
        var imageCache = yrprxComponentsFactory.getImgCacheService();
        var props = imageCache.findEntryProperties(uriObject);
        if (!props)
            throw "Cannot get properties from cache";

        var contentType = props.get("type", nsISupportsCString);
        if (!contentType)
            throw "Cannot get type from cache";

        var mimeService = yrprxComponentsFactory.getMIMEService();
        ext = mimeService.getPrimaryExtension(contentType, "");
        if (!ext)
            throw "Cannot get extension for mime-type";
    }
    catch(ex)
    {
        if (this.logger.enabled) this.logger.error("getExtension: Exception: " + ex);
        //if we cannot get extension then let's add .jpg
        ext = "jpg";
    }

    return ext;
}

wsshSaveImageHelper.getPad2Suffix = function ()
{
    if (this.suffix < 10)
        return "0" + (this.suffix++);
    else
        return this.suffix++;
}

wsshSaveImageHelper.getDefaultFileName = function (uriObject)
{
    var defaultFileName = yrprxUtil.getFileNameWithExtensionFromPath(uriObject.path);

    if (defaultFileName.indexOf('?') != -1 || defaultFileName.indexOf('&') != -1)
        defaultFileName = "";

    if (defaultFileName == "")
    {
        if (this.suffix == 0)
        {
            this.baseName = new String(new Date().getTime());
            if (this.baseName.length > 7) // trim file name
                this.baseName = this.baseName.substring(this.baseName.length-7);
        }
        defaultFileName = this.baseName + this.getPad2Suffix();
    }

    return defaultFileName;
}

wsshSaveImageHelper.saveImage = function (src)
{
    try
    {
        if (this.logger.enabled) this.logger.debug("saveImage: " + src);
        if (!src || !src.length)
            throw "Invalid image URL!";

        var uriObject = yrprxComponentsFactory.getIOService().newURI(src, null, null);

        this.suffix = 0; // reset suffix
        var defaultFileName = this.getDefaultFileName(uriObject);
        var ext = yrprxUtil.getExtension(defaultFileName);
        if (ext == "")
        {
            ext = this.getExtension(uriObject);
            defaultFileName += "." + ext;
        }

        var fp = yrprxComponentsFactory.createFilePicker();
        // init file picker
        fp.init(window, wsshResources["webslideshow.filepicker.save.image"], nsIFilePicker.modeSave);
        fp.appendFilter(wsshResources["webslideshow.filepicker.filter.all"], "*.*");
        fp.defaultString = defaultFileName;
        fp.defaultExtension = ext;
        // open file picker
        if (fp.show() == nsIFilePicker.returnCancel)
            return;

        yrprxHTMLContentHelper.saveImage(src, fp.file);
    }
    catch(ex)
    {
        if (this.logger.enabled) this.logger.error("saveImage: Exception: " + ex);
    }
}

wsshSaveImageHelper.saveAllImages = function (sources)
{
    try
    {
        if (!sources || !sources.length)
            throw "Nothing to save!";

        var fp = yrprxComponentsFactory.createFilePicker();
        // init file picker
        fp.init(window, wsshResources["webslideshow.filepicker.save.all.images"], nsIFilePicker.modeGetFolder);
        // open file picker
        if (fp.show() == nsIFilePicker.returnCancel)
            return;

        this.suffix = 0; // reset suffix
        wsshWindowManager.openSaveImagesProgressDialog(sources, fp.file);
    }
    catch(ex)
    {
        if (this.logger.enabled) this.logger.error("saveAllImages: Exception: " + ex);
    }
}

wsshSaveImageHelper.getImageFileName = function (destFolder, src)
{
    if (!this.ioService)
        this.ioService = yrprxComponentsFactory.getIOService();

    var uriObject = this.ioService.newURI(src, null, null);

    var defaultFileName = this.getDefaultFileName(uriObject);
    if (yrprxUtil.getExtension(defaultFileName) == "")
        defaultFileName += "." + this.getExtension(uriObject);

    var file = yrprxComponentsFactory.createLocalFile();
    file.initWithFile(destFolder);
    file.append(defaultFileName);
    return file;
}
